package fr.castorhoz.isi_connectivity_widget.gps_widget;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import fr.castorhoz.isi_connectivity_widget.ConnButton;
import fr.castorhoz.isi_connectivity_widget.R;
import fr.castorhoz.isi_connectivity_widget.database.DBAdapter;
import fr.castorhoz.isi_connectivity_widget.database.DataBaseHelper;

public class GPSButton extends ConnButton {
	
	public final static String PROVIDERS_CHANGED_ACTION = "android.location.PROVIDERS_CHANGED";
	
	private static DBAdapter db;
	private Context context;

	public static GpsStatus.Listener gpsListener = new GpsStatus.Listener() {

		public void onGpsStatusChanged(int event) {
			switch (event) {
			case GpsStatus.GPS_EVENT_STARTED:
				Log.i(this.getClass().toString(), "GPS EVENT STARTED");
				break;
			case GpsStatus.GPS_EVENT_STOPPED:
				Log.i(this.getClass().toString(), "GPS_EVENT_STOPPED");
				break;
			}
		}
	};
	

	public GPSButton(Context context) {

		this.context = context;
		getLocationManager(context).addGpsStatusListener(gpsListener);
		
		Log.d(this.getClass().getName(), "detecting gps connectivity");
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		registerGPSStateInDatabase(lm.isProviderEnabled(LocationManager.GPS_PROVIDER));
	}
	
	private void registerGPSStateInDatabase(boolean GPSProviderEnabled) {
		Log.i(this.getClass().getName(), "registering gps state : "+GPSProviderEnabled);
		db = new DBAdapter(context);
		db.open();
		db.removeGPSWidgetStates();
		db.insertGPSWidgetState(String.valueOf(GPSProviderEnabled));
		db.close();
		Log.d(this.getClass().getName(), "GPS state is saved into database");
	}

	/**
	 * Generic button. Do not use this to add a button to into a widget
	 */
	public GPSButton() {}

	@Override
	public void enableNetwork(Context context) {
		String provider = Settings.Secure.getString(
				context.getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		Log.d(this.getClass().getName(), "location providers found : "+provider);
		if (!provider.contains("gps")) {
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			context.getApplicationContext().sendBroadcast(poke);

		}
	}

	@Override
	public void disableNetwork(Context context) {
		String provider = Settings.Secure.getString(
				context.getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		
		Log.d(this.getClass().getName(), "location providers found : "+provider);
		if (provider.contains("gps")) {
			Log.d(this.getClass().getName(), "sending poke");
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			context.getApplicationContext().sendBroadcast(poke);

		}
//		Settings.Secure.setLocationProviderEnabled(
//                context.getContentResolver(), LocationManager.GPS_PROVIDER, false);
	}

	private LocationManager getLocationManager(Context context) {
		return (LocationManager) context.getApplicationContext()
				.getSystemService(Context.LOCATION_SERVICE);
	}

	@Override
	public String getAction() {
		return "fr_imberle_connectivityWidget_CLICK_GPS";
	}

	@Override
	public int getSelectorOff() {
		return R.drawable.gps_selector_off;
	}

	@Override
	public int getSelectorOn() {
		return R.drawable.gps_selector_on;
	}

	@Override
	public int getSelectorUnknown() {
		return R.drawable.gps_selector_unknown;
	}

	@Override
	public int getCurrentSelector() {
		return getGPSStateFromDatabse(context) ? getSelectorOn() : getSelectorOff();
	}

	/**
	 * Gets the state of mobile data (enabled/disabled) from database
	 * @param context
	 * @return
	 */
	public static boolean getGPSStateFromDatabse(Context context) {
		db = new DBAdapter(context);
        String gpsState = null;
        db.open();
        Cursor c = db.getGPSWidgetState();
        if (c.moveToNext()) {
        	Log.d(GPSButton.class.getName(), "cursor not empty");
                gpsState = c.getString(c.getColumnIndexOrThrow(DataBaseHelper.GPS_STATE_COLUMNNAME));
        }
    	Log.d(GPSButton.class.getName(), "gpsState value : "+gpsState);
        c.close();
        db.close();
        return gpsState != null && gpsState.equals(String.valueOf(true));
	}

	@Override
	public boolean getState(Context context) {
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}
	
}
